package com.study.crypto.asn1.sm2;

import org.bouncycastle.asn1.*;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;

import java.security.InvalidParameterException;

/**
 * 密钥对保护数据格式，见 {@code <GB-T 35276_2017_信息安全技术_SM2密码算法使用规范>} 第 7.4 章节
 * @author Songjin
 * @since 2021-02-28 23:25
 */
public class SM2EnvelopedKey extends ASN1Object {
    
    /** 对称密码算法标识 */
    private final AlgorithmIdentifier symAlgID;
    /** 对称密钥密文 */
    private final ASN1Sequence        symEncryptedKey;
    /** sm2 公钥 */
    private final ASN1BitString       sm2PublicKey;
    /** sm2 私钥密文 */
    private final ASN1BitString       sm2EncryptedPrivateKey;
    
    public SM2EnvelopedKey(AlgorithmIdentifier symAlgID, ASN1Sequence symEncryptedKey, ASN1BitString sm2PublicKey, ASN1BitString sm2EncryptedPrivateKey) {
        if (symAlgID == null) {
            throw new InvalidParameterException("symAlgID参数错误");
        }
        if (symEncryptedKey == null) {
            throw new InvalidParameterException("symEncryptedKey参数错误");
        }
        if (sm2PublicKey == null) {
            throw new InvalidParameterException("sm2PublicKey参数错误");
        }
        if (sm2EncryptedPrivateKey == null) {
            throw new InvalidParameterException("sm2EncryptedPrivateKey参数错误");
        }
        this.symAlgID = symAlgID;
        this.symEncryptedKey = symEncryptedKey;
        this.sm2PublicKey = sm2PublicKey;
        this.sm2EncryptedPrivateKey = sm2EncryptedPrivateKey;
    }
    
    @Override
    public ASN1Primitive toASN1Primitive() {
        ASN1EncodableVector v = new ASN1EncodableVector(6);
        v.add(symAlgID);
        v.add(symEncryptedKey);
        v.add(sm2PublicKey);
        v.add(sm2EncryptedPrivateKey);
        return new DERSequence(v);
    }
    
}
